import { useState, useEffect, useRef, useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
  Send,
  Trash2,
  Settings,
  Download,
  Copy,
  Bot,
  User,
  Loader2,
  AlertCircle,
  Sparkles,
  History,
  Plus,
  Search,
} from 'lucide-react';
import {
  getProviders,
  callAIStream,
  getChatSessions,
  createNewSession,
  updateSession,
  deleteSession,
  getCurrentSessionId,
  setCurrentSessionId,
  generateSessionTitle,
  type AIProvider,
  type AIModel,
  type ChatMessage,
  type ChatConfig,
  type ChatSession,
} from '@/lib/ai-config';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Link } from 'react-router-dom';

/**
 * AI Playground - AI 对话测试平台
 * 支持阿里云百炼、DeepSeek、Ollama 等多个平台
 */
export default function AIPlayground() {
  const [providers, setProviders] = useState<AIProvider[]>([]);
  const [selectedProvider, setSelectedProvider] = useState<AIProvider | null>(null);
  const [selectedModel, setSelectedModel] = useState<AIModel | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showSettings, setShowSettings] = useState(false);
  const [config, setConfig] = useState<ChatConfig>({
    temperature: 0.7,
    maxTokens: 2000,
    topP: 0.9,
    stream: true,
  });

  // 会话管理状态
  const [sessions, setSessions] = useState<ChatSession[]>([]);
  const [currentSessionId, setCurrentSessionIdState] = useState<string | null>(null);
  const [showHistory, setShowHistory] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');

  const messagesEndRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // 加载配置和历史
  useEffect(() => {
    const loadedProviders = getProviders();
    setProviders(loadedProviders);
    
    // 选择第一个启用的提供商
    const firstEnabled = loadedProviders.find(p => p.enabled);
    if (firstEnabled) {
      setSelectedProvider(firstEnabled);
      setSelectedModel(firstEnabled.models[0]);
    }

    // 加载会话列表
    let loadedSessions = getChatSessions();
    
    // 如果没有会话，创建默认会话
    if (loadedSessions.length === 0) {
      const newSession = createNewSession();
      loadedSessions = [newSession];
    }
    
    setSessions(loadedSessions);
    
    // 加载当前会话
    let currentId = getCurrentSessionId();
    if (!currentId || !loadedSessions.find(s => s.id === currentId)) {
      currentId = loadedSessions[0].id;
      setCurrentSessionId(currentId);
    }
    
    setCurrentSessionIdState(currentId);
    const currentSession = loadedSessions.find(s => s.id === currentId);
    if (currentSession) {
      setMessages(currentSession.messages);
    }
  }, []);

  const needProviderConfig = useMemo(() => {
    return providers.length === 0 || providers.every(p => !p.enabled || !p.apiKey);
  }, [providers]);

  // 自动滚动到底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const handleSend = async () => {
    if (!input.trim() || !selectedProvider || !selectedModel || loading) return;

    const userMessage: ChatMessage = {
      id: `msg-${Date.now()}`,
      role: 'user',
      content: input.trim(),
      timestamp: Date.now(),
      model: selectedModel.name,
      provider: selectedProvider.name,
    };

    const newMessages = [...messages, userMessage];
    setMessages(newMessages);
    setInput('');
    setLoading(true);
    setError(null);

    // 创建助手消息占位
    const assistantMessage: ChatMessage = {
      id: `msg-${Date.now() + 1}`,
      role: 'assistant',
      content: '',
      timestamp: Date.now(),
      model: selectedModel.name,
      provider: selectedProvider.name,
    };

    setMessages([...newMessages, assistantMessage]);

    try {
      let fullContent = '';
      
      // 流式接收响应
      for await (const chunk of callAIStream(
        selectedProvider,
        selectedModel,
        newMessages,
        config
      )) {
        fullContent += chunk;
        setMessages(prev => {
          const updated = [...prev];
          updated[updated.length - 1] = {
            ...updated[updated.length - 1],
            content: fullContent,
          };
          return updated;
        });
      }

      // 保存到当前会话
      const finalMessages = [...newMessages, { ...assistantMessage, content: fullContent }];
      if (currentSessionId) {
        // 如果是第一条消息，自动生成标题
        const updates: Partial<ChatSession> = {
          messages: finalMessages,
        };
        
        if (finalMessages.length === 2) { // 第一对对话
          updates.title = generateSessionTitle(userMessage.content);
          updates.provider = selectedProvider?.name;
          updates.model = selectedModel?.name;
        }
        
        updateSession(currentSessionId, updates);
        
        // 更新本地会话列表
        setSessions(prev => prev.map(s => 
          s.id === currentSessionId 
            ? { ...s, ...updates, updatedAt: Date.now() }
            : s
        ));
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '发送失败');
      // 移除失败的消息
      setMessages(newMessages);
    } finally {
      setLoading(false);
    }
  };

  const handleClear = () => {
    if (confirm('确定要清空当前对话吗？')) {
      setMessages([]);
      if (currentSessionId) {
        updateSession(currentSessionId, { messages: [] });
        setSessions(prev => prev.map(s => 
          s.id === currentSessionId 
            ? { ...s, messages: [], updatedAt: Date.now() }
            : s
        ));
      }
    }
  };

  const handleNewChat = () => {
    const newSession = createNewSession();
    // 使用函数式更新确保获取最新状态
    setSessions(prev => [newSession, ...prev]);
    setCurrentSessionIdState(newSession.id);
    setMessages([]);
  };

  const handleSwitchSession = (sessionId: string) => {
    setCurrentSessionIdState(sessionId);
    setCurrentSessionId(sessionId);
    const session = sessions.find(s => s.id === sessionId);
    if (session) {
      setMessages(session.messages);
    }
  };

  const handleDeleteSession = (sessionId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    if (confirm('确定要删除这个对话吗？')) {
      // 先计算删除后的剩余会话（使用当前状态）
      const remaining = sessions.filter(s => s.id !== sessionId);
      
      // 从localStorage删除
      deleteSession(sessionId);
      
      // 更新UI状态
      setSessions(remaining);
      
      // 如果删除的是当前会话，需要切换
      if (sessionId === currentSessionId) {
        if (remaining.length > 0) {
          // 切换到第一个剩余会话
          handleSwitchSession(remaining[0].id);
        } else {
          // 如果没有剩余会话，创建新会话
          const newSession = createNewSession();
          setSessions([newSession]);
          setCurrentSessionIdState(newSession.id);
          setMessages([]);
        }
      }
    }
  };

  const handleExport = () => {
    const data = JSON.stringify(messages, null, 2);
    const blob = new Blob([data], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `chat-${new Date().toISOString().split('T')[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleCopy = (content: string) => {
    navigator.clipboard.writeText(content);
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <div className="flex h-[calc(100vh-8rem)] gap-4">
      {needProviderConfig && (
        <div className="absolute left-0 right-0 top-0 z-10 mx-4 mt-4">
          <div className="rounded-lg border bg-amber-50 p-3 text-sm text-amber-900">
            <div className="flex items-start justify-between gap-2">
              <div className="flex-1">
                未检测到可用的 AI 提供商，请前往设置页面配置并启用 API Key。
              </div>
              <Link to="/app/settings">
                <Button size="sm" variant="outline">前往设置</Button>
              </Link>
            </div>
          </div>
        </div>
      )}
      {/* 历史对话侧边栏 */}
      {showHistory && (
        <Card className="w-64 flex flex-col">
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between mb-2">
              <CardTitle className="text-sm flex items-center gap-2">
                <History className="h-4 w-4" />
                历史对话
              </CardTitle>
              <Button size="sm" variant="ghost" className="h-8 w-8 p-0" onClick={handleNewChat}>
                <Plus className="h-4 w-4" />
              </Button>
            </div>
            <div className="relative">
              <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="搜索对话..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="h-9 pl-8"
              />
            </div>
          </CardHeader>
          <CardContent className="flex-1 overflow-y-auto p-2 space-y-1">
            {sessions
              .filter(s => s.title.toLowerCase().includes(searchQuery.toLowerCase()))
              .map((session) => (
                <div
                  key={session.id}
                  onClick={() => handleSwitchSession(session.id)}
                  className={`group flex items-start justify-between gap-2 p-2 rounded-md cursor-pointer transition-colors hover:bg-accent ${
                    session.id === currentSessionId ? 'bg-accent' : ''
                  }`}
                >
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium truncate">
                      {session.title}
                    </div>
                    <div className="text-xs text-muted-foreground flex items-center gap-1">
                      <span>{new Date(session.updatedAt).toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' })}</span>
                      {session.messages.length > 0 && (
                        <>
                          <span>·</span>
                          <span>{session.messages.length} 条</span>
                        </>
                      )}
                    </div>
                  </div>
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity"
                    onClick={(e) => handleDeleteSession(session.id, e)}
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              ))}
            {sessions.filter(s => s.title.toLowerCase().includes(searchQuery.toLowerCase())).length === 0 && (
              <div className="text-center text-sm text-muted-foreground py-8">
                {searchQuery ? '没有找到匹配的对话' : '暂无历史对话'}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 主对话区域 */}
      <div className="flex flex-1 flex-col">
        {/* 头部 */}
        <Card className="mb-4">
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Sparkles className="h-6 w-6 text-primary" />
                <div>
                  <CardTitle>AI Playground</CardTitle>
                  <p className="text-sm text-muted-foreground">
                    {selectedProvider?.name} - {selectedModel?.name}
                  </p>
                </div>
              </div>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setShowHistory(!showHistory)}
                >
                  <History className="mr-2 h-4 w-4" />
                  {showHistory ? '隐藏历史' : '显示历史'}
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setShowSettings(!showSettings)}
                >
                  <Settings className="mr-2 h-4 w-4" />
                  {showSettings ? '隐藏设置' : '显示设置'}
                </Button>
                <Button variant="outline" size="sm" onClick={handleExport}>
                  <Download className="mr-2 h-4 w-4" />
                  导出
                </Button>
                <Button variant="outline" size="sm" onClick={handleClear}>
                  <Trash2 className="mr-2 h-4 w-4" />
                  清空
                </Button>
              </div>
            </div>
          </CardHeader>
        </Card>

        {/* 消息列表 */}
        <Card className="mb-4 flex-1 overflow-hidden">
          <CardContent className="h-full overflow-y-auto p-4">
            {messages.length === 0 ? (
              <div className="flex h-full flex-col items-center justify-center text-center">
                <Bot className="mb-4 h-12 w-12 text-muted-foreground" />
                <h3 className="mb-2 text-lg font-semibold">开始对话</h3>
                <p className="text-sm text-muted-foreground">
                  选择模型，输入消息开始与 AI 对话
                </p>
              </div>
            ) : (
              <div className="space-y-4">
                {messages.map((message) => (
                  <div
                    key={message.id}
                    className={`flex gap-3 ${
                      message.role === 'user' ? 'justify-end' : 'justify-start'
                    }`}
                  >
                    {message.role === 'assistant' && (
                      <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary">
                        <Bot className="h-4 w-4 text-primary-foreground" />
                      </div>
                    )}
                    <div
                      className={`max-w-[80%] rounded-lg p-3 ${
                        message.role === 'user'
                          ? 'bg-primary text-primary-foreground'
                          : 'bg-muted'
                      }`}
                    >
                      <div className="prose prose-sm dark:prose-invert max-w-none">
                        <ReactMarkdown remarkPlugins={[remarkGfm]}>
                          {message.content}
                        </ReactMarkdown>
                      </div>
                      <div className="mt-2 flex items-center justify-between gap-2">
                        <span className="text-xs opacity-70">
                          {new Date(message.timestamp).toLocaleTimeString('zh-CN')}
                        </span>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-6 px-2"
                          onClick={() => handleCopy(message.content)}
                        >
                          <Copy className="h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                    {message.role === 'user' && (
                      <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-secondary">
                        <User className="h-4 w-4" />
                      </div>
                    )}
                  </div>
                ))}
                {loading && (
                  <div className="flex justify-start gap-3">
                    <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary">
                      <Bot className="h-4 w-4 text-primary-foreground" />
                    </div>
                    <div className="rounded-lg bg-muted p-3">
                      <Loader2 className="h-4 w-4 animate-spin" />
                    </div>
                  </div>
                )}
                <div ref={messagesEndRef} />
              </div>
            )}
          </CardContent>
        </Card>

        {/* 错误提示 */}
        {error && (
          <Card className="mb-4 border-destructive">
            <CardContent className="flex items-center gap-2 p-3">
              <AlertCircle className="h-5 w-5 text-destructive" />
              <span className="text-sm">{error}</span>
            </CardContent>
          </Card>
        )}

        {/* 输入区域 */}
        <Card>
          <CardContent className="p-4">
            <div className="flex gap-2">
              <textarea
                ref={textareaRef}
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="输入消息... (Shift+Enter 换行)"
                className="min-h-[60px] flex-1 resize-none rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                disabled={loading}
              />
              <Button
                onClick={handleSend}
                disabled={!input.trim() || loading || !selectedProvider || !selectedModel}
                className="self-end"
              >
                {loading ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Send className="h-4 w-4" />
                )}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 设置面板 */}
      {showSettings && (
        <Card className="w-80">
          <CardHeader>
            <CardTitle>设置</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 提供商选择 */}
            <div>
              <label className="mb-2 block text-sm font-medium">AI 提供商</label>
              <select
                value={selectedProvider?.id || ''}
                onChange={(e) => {
                  const provider = providers.find(p => p.id === e.target.value);
                  setSelectedProvider(provider || null);
                  setSelectedModel(provider?.models[0] || null);
                }}
                className="w-full rounded-md border bg-background px-3 py-2 text-sm"
              >
                {providers.filter(p => p.enabled).map((provider) => (
                  <option key={provider.id} value={provider.id}>
                    {provider.name}
                  </option>
                ))}
              </select>
            </div>

            {/* 模型选择 */}
            <div>
              <label className="mb-2 block text-sm font-medium">模型</label>
              <select
                value={selectedModel?.id || ''}
                onChange={(e) => {
                  const model = selectedProvider?.models.find(m => m.id === e.target.value);
                  setSelectedModel(model || null);
                }}
                className="w-full rounded-md border bg-background px-3 py-2 text-sm"
              >
                {selectedProvider?.models.map((model) => (
                  <option key={model.id} value={model.id}>
                    {model.name}
                  </option>
                ))}
              </select>
              {selectedModel?.description && (
                <p className="mt-1 text-xs text-muted-foreground">
                  {selectedModel.description}
                </p>
              )}
            </div>

            <Separator />

            {/* 参数配置 */}
            <div>
              <label className="mb-2 block text-sm font-medium">
                Temperature: {config.temperature}
              </label>
              <input
                type="range"
                min="0"
                max="2"
                step="0.1"
                value={config.temperature}
                onChange={(e) =>
                  setConfig({ ...config, temperature: parseFloat(e.target.value) })
                }
                className="w-full"
              />
              <p className="mt-1 text-xs text-muted-foreground">
                控制输出的随机性，值越高越随机
              </p>
            </div>

            <div>
              <label className="mb-2 block text-sm font-medium">
                Max Tokens: {config.maxTokens}
              </label>
              <input
                type="range"
                min="100"
                max="8000"
                step="100"
                value={config.maxTokens}
                onChange={(e) =>
                  setConfig({ ...config, maxTokens: parseInt(e.target.value) })
                }
                className="w-full"
              />
              <p className="mt-1 text-xs text-muted-foreground">
                最大生成的 token 数量
              </p>
            </div>

            <div>
              <label className="mb-2 block text-sm font-medium">
                Top P: {config.topP}
              </label>
              <input
                type="range"
                min="0"
                max="1"
                step="0.1"
                value={config.topP}
                onChange={(e) =>
                  setConfig({ ...config, topP: parseFloat(e.target.value) })
                }
                className="w-full"
              />
              <p className="mt-1 text-xs text-muted-foreground">
                控制输出的多样性
              </p>
            </div>

            <Separator />

            {/* 统计信息 */}
            <div className="space-y-2 rounded-lg bg-muted p-3">
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">消息数量</span>
                <Badge variant="secondary">{messages.length}</Badge>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">当前提供商</span>
                <Badge>{selectedProvider?.name}</Badge>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">当前模型</span>
                <Badge>{selectedModel?.name}</Badge>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

